<script lang="ts" setup>
import { ElMessage } from "element-plus"
import { reactive, ref } from "vue"
import { useRouter } from "vue-router"
import type { FormInstance, FormRules } from "element-plus"
import { Key, Loading, Lock, Picture, User } from "@element-plus/icons-vue"
import { useUserStore } from "@/store/modules/user"
import { getToken } from "@/utils/cache/cookies"
import { loginApi, registerApi } from "@/api/user"
import logo from "@/assets/layouts/logo.png?url"

const router = useRouter()
const userStore = useUserStore()

/** 登录表单元素的引用 */
const loginFormRef = ref<FormInstance | null>(null)

const registerFormRef = ref<FormInstance | null>(null)

/** 登录按钮 Loading */
const loading = ref(false)

/** 登录表单数据 */
const loginFormData = reactive({
  username: "admin1",
  password: "12345678"
})
const register = reactive({
  username: "admin1",
  password: "12345678",
  repeatPassword: ""
})

/** 登录表单校验规则 */
const loginFormRules: FormRules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 5, max: 16, message: "长度在 6 到 16 个字符", trigger: "blur" }
  ]
}
const registerFormRules: FormRules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 8, max: 16, message: "长度在 8 到 16 个字符", trigger: "blur" }
  ]
}

/** 登录 */
function handleLogin() {
  loginFormRef.value?.validate((valid) => {
    if (!valid) {
      ElMessage.error("校验不通过")
      return
    }
    loading.value = true
    loginApi(loginFormData)
      .then(({ code, data }) => {
        if (code === 200) {
          userStore.setToken(data)
          userStore.getInfo()
          router.push("/")
        }
      })
      .catch(() => {
        loginFormData.password = ""
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const repeatPasswordRule = [
  {
    validator: (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入确认密码"))
      } else if (register.password !== value) {
        callback(new Error("两次密码不一致!"))
      } else {
        callback()
      }
    },
    trigger: "blur"
  }
]
// 1 登录 2 注册
const type = ref("1")
const changeType = (val) => {
  type.value = val
}
function handleRegister() {
  registerFormRef.value?.validate((valid) => {
    if (!valid) {
      ElMessage.error("校验不通过")
      return
    }
    loading.value = true
    registerApi(register)
      .then(({ data }) => {
        ElMessage.success("注册成功，请登录")
        type.value = "1"
        loginFormData.username = data.username
        loginFormData.password = ""
      })
      .catch(() => {})
      .finally(() => {
        loading.value = false
      })
  })
}
</script>

<template>
  <div class="login-container">
    <div class="logo-wrap">
      <img src="@/assets/layouts/logo.png" alt="" class="logo" />
      <span>数据库智能交互系统</span>
    </div>
    <img src="@/assets/images/login-img.png" alt="" class="login-img" />
    <div class="login-card">
      <div class="title">欢迎{{ type == "1" ? "登录" : "注册" }}</div>
      <div class="content" v-if="type == '1'">
        <el-form ref="loginFormRef" :model="loginFormData" :rules="loginFormRules" @keyup.enter="handleLogin">
          <el-form-item prop="username">
            <el-input
              v-model.trim="loginFormData.username"
              placeholder="用户名"
              type="text"
              tabindex="1"
              :prefix-icon="User"
              size="large"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model.trim="loginFormData.password"
              placeholder="密码"
              type="password"
              tabindex="2"
              :prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
          <el-button :loading="loading" type="primary" size="large" @click.prevent="handleLogin"> 登 录 </el-button>
        </el-form>
        <el-button size="large" @click.prevent="changeType('2')"> 注 册 </el-button>
      </div>
      <div class="content" v-if="type == '2'">
        <el-form ref="registerFormRef" :model="register" :rules="registerFormRules" @keyup.enter="handleRegister">
          <el-form-item prop="username">
            <el-input
              v-model.trim="register.username"
              placeholder="用户名"
              type="text"
              tabindex="1"
              :prefix-icon="User"
              size="large"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model.trim="register.password"
              placeholder="密码"
              type="password"
              tabindex="2"
              :prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
          <el-form-item prop="repeatPassword" :rules="repeatPasswordRule">
            <el-input
              v-model.trim="register.repeatPassword"
              placeholder="再次输入密码"
              type="password"
              tabindex="2"
              :prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
          <el-button :loading="loading" type="primary" size="large" @click.prevent="handleRegister"> 注册 </el-button>
        </el-form>
        <el-button size="large" @click.prevent="changeType(1)"> 返回 </el-button>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.logo-wrap {
  position: absolute;
  left: 20px;
  top: 1vh;
  display: flex;
  align-items: center;
  padding: 40px;
  font-weight: 500;
  font-size: 26px;
  color: #333333;
  .logo {
    width: 52px;
    height: 52px;
    margin-right: 16px;
  }
}
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 100%;
  background-image: url(../../assets/images/login-bg.png);
  background-size: 100% 100%;
  .theme-switch {
    position: fixed;
    top: 5%;
    right: 5%;
    cursor: pointer;
  }
  .login-img {
    width: 570px;
    height: 530px;
    margin-right: 200px;
  }
  .login-card {
    background: rgba(255, 255, 255, 0.5);
    box-shadow: 0px 2px 24px 0px rgba(197, 208, 231, 0.3);
    border-radius: 8px;
    border: 2px solid #ffffff;
    width: 360px;
    // max-width: 90%;
    // border-radius: 20px;
    // box-shadow: 0 0 10px #dcdfe6;
    // background-color: var(--el-bg-color);
    overflow: hidden;
    .title {
      font-size: 20px;
      font-weight: bold;
      text-align: center;
      padding-top: 32px;
    }
    .content {
      padding: 32px;
      :deep(.el-input-group__append) {
        padding: 0;
        overflow: hidden;
        .el-image {
          width: 100px;
          height: 40px;
          border-left: 0px;
          user-select: none;
          cursor: pointer;
          text-align: center;
        }
      }
      .el-button {
        width: 100%;
        margin-top: 10px;
      }
    }
  }
}
</style>
